//var net = require('net');
//var clients = [];
//
//var server = net.createServer(function (client) {
//    client.on("connect", onConnect);
//    client.on("data", onData);
//
//    client.addListener("end", function() {
//    clients.splice(clients.indexOf(client),1);
//    client.end();
//    });
//
//    clients.push(client);
//});
//
//function onData(d){
//    console.log("From Flash = " + d);
//    clients.forEach(function(client){
//        client.write(d);
//    });
//}
//
//function onConnect(){
//  console.log("Connection");
//}
//
//server.listen(1337);


var net = require('net');
var clients = [];

function policy() {
  var xml = '<?xml version="1.0"?>\n<!DOCTYPE cross-domain-policy SYSTEM'
          + ' "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">\n<cross-domain-policy>\n';

  xml += '<allow-access-from domain="*" to-ports="*"/>\n';
  xml += '</cross-domain-policy>\n';

  return xml;
}

server = net.createServer(function (socket) {

//  socket.setEncoding('utf8');
//  socket.write(policy() + '\0');
socket.on('data', on_policy_check);
  function on_policy_check(data) {
    console.log("PolicyCheck = " + data);

    socket.removeListener('data', on_policy_check);
    socket.on('data', on_data);

    if(data == '<policy-file-request/>\0'){
       console.dir("writing policy");
       socket.write(policy() + '\0');
    }
    else{
        on_data(data);
    }
  }

  function on_data(data) {
      //console.log("On data = " + data);
      clients.forEach(function(socket){
         socket.write(data);
      });
  }



//  socket.on('error', function(err){
//    if(socket && socket.end){
//      socket.end();
//      socket.destroy();
//    }
//  });

  socket.on('connect', function () {

  });

  socket.on('end', function () {
    clients.splice(clients.indexOf(socket),1);
    socket.end();
  });

  clients.push(socket);
});

server.listen(1337);